import React from 'react'
import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import { AtButton } from 'taro-ui'
import { request } from '@/utils'
import './index.less'

const Authorize = () => {
  const handleAuthorize  = () => {
    Taro.showLoading()
    const openId = Taro.getStorageSync('openId')
    Taro.getSetting({
      success(res) {
        if(!res.authSetting['scope.getUserInfo']) {
         Taro.getUserInfo({
           async success() {
             const data = await request({url: 'hkshihua/user/autoLogin', data: {source: 0, openId}, isAuth: true})
             if(data.error) {
              Taro.redirectTo({url: '/pages/login/index'})
              return
            }
             const response = await request({url: 'hkshihua/user/getAllprofile', header: {token: data.token}}) 
              if(response.error) return
              Taro.setStorage({key: 'userInfo', data: JSON.stringify({token: data.token, user: response.authUser})}).then(() => {
              if(response.authUser.role == 'OPERATOR') {
                Taro.switchTab({url: '/pages/scanQRCode/index'}) 
              } else {
                Taro.switchTab({url: '/pages/index/index'})
              }
              })
           }
         })
        }
      }
    })
  }
  return <View className='authorize'>
    <View className='title'>鑫满人生</View>
    <View className='line'></View>
    <View className='text'>登录后开发者将获取以下权限</View>
    <View className='text'>·获得您的公开信息</View>
    <View className='footer'>
        <AtButton onClick={handleAuthorize} openType='getUserInfo'>授权登录</AtButton>
    </View>
  </View>
}

export default Authorize